package cn.chilemou;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author LiXingShuai
 * @className RabbitConsumer
 * @description: TODO
 * @date 2023年04月10日
 * @version: 1.0
 */
public class RabbitConsumer {
    private static final String EXCHANGE_NAME ="exchange_demo";
    private static final String ROUTING_KEY ="routingKey_demo";
    private static final String QUEUE_MAME ="queue_demo";

    private static final String IP_ADDRESS ="47.94.171.202";

    private static final int PORT = 5672;

    private static final String USERNAME = "likoukou";
    private static final String PWD = "likoukou";

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        Address[] addresses = new Address[]{new Address(IP_ADDRESS,PORT)};
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUsername(USERNAME);
        connectionFactory.setPassword(PWD);
        connectionFactory.setVirtualHost("host1");
        // 这里的链接方式与生产者的demo略有不同，注意辨别区别
        Connection connection = connectionFactory.newConnection(addresses);
        final Channel channel = connection.createChannel();
        channel.basicQos(64);// 设置客户端最多接受未被ack的消息个数
        boolean autoAck = false;
        channel.basicConsume(QUEUE_MAME,autoAck,"myConsumerTag",new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //super.handleDelivery(consumerTag, envelope, properties, body);
                System.out.println(consumerTag);
                System.out.println(envelope.getRoutingKey());
                System.out.println(properties.getContentType());
                System.out.println(envelope.getDeliveryTag());
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        });
        // 等待回调函数执行完毕后，关闭资源
        TimeUnit.SECONDS.sleep(3);
        channel.close();
        connection.close();
    }
}
